<template>
  <div class="tab">
    <el-row>
      <el-col :span="2" class="work">工作台</el-col>
      <el-col :span="22">
        <el-tabs v-model="activeIndex" type="border-card" closable  @tab-click="tabClick" v-if="options.length"
                 @tab-remove="tabRemove">
          <el-tab-pane
            :key="item.name"
            v-for="(item, index) in options"
            :label="item.name"
            :name="item.route">
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    data() {
      return {
      
      }
    },
    methods: {
      tabClick () {
        this.$router.push({path: this.activeIndex});
      },
      tabRemove (targetName) {
        // 首页不可删除
        if(targetName == '/homePage') {
          return;
        }
        this.$store.commit('delete_tabs', targetName);
        if (this.activeIndex === targetName) {
          // 设置当前激活的路由
          if (this.options && this.options.length >= 1) {
            this.$store.commit('set_active_index', this.options[this.options.length-1].route);
            this.$router.push({path: this.activeIndex});
          } else {
            this.$router.push({path: '/homePage'});
          }
        }
      }
    },
    computed: {
      options () {
        return this.$store.state.options;
      },
      activeIndex: {
        get () {
          return this.$store.state.activeIndex;
        },
        set (val) {
          this.$store.commit('set_active_index', val);
        }
      }
    },
    watch: {
      '$route'(to) {
        let flag = false;
        for (let option of this.options ) {
          if (option.name === to.name) {
            flag = true;
            this.$store.commit('set_active_index', to.path);
            break
          }
        }
        if (!flag) {
          this.$store.commit('add_tabs', {route: to.path, name: to.name});
          this.$store.commit('set_active_index', to.path);
        }
      }
    }
  }

</script>

<style lang='scss'>
  .tab {
    .work {
      text-align: center;
      line-height: 38px;
      background-color: #fff;
      border: 1px solid #d8dce5;
      box-shadow: 0 2px 4px 0 rgba(0,0,0,.12), 0 0 6px 0 rgba(0,0,0,.04);
    }
    .el-tabs--border-card>.el-tabs__content {
      padding: 0;
    }
  }
</style>
